package com.woniu.info.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

//@Component
@Slf4j
public class MessageCallBackConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        // 队列接收失败，如果不配置，那么将直接丢弃该消息，也可以选择在yml中进行配置：publisher-returns: true
        //rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            System.out.println("交换机接收成功");
        }else{
            System.out.println("交换机接收失败，失败的原因是：" + cause);
            System.out.println("交换机接收失败，失败的消息是：" + new String(correlationData.getReturnedMessage().getBody()));
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("队列没有接收到消息，返回的信息是：{}，错误码：{}，错误的原因：{}，交换机名称：{}，路由key：{}",
                new String(message.getBody()),
                replyCode,
                replyText,
                exchange,
                routingKey);
    }
}
